package org.lhh.server.common.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.pentaho.di.repository.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class EhcacheUtil {

    private static final Logger log = LoggerFactory.getLogger(EhcacheUtil.class);

    @Autowired
    private CacheManager manager;


    public void removeAll(String cacheName) {
        try {
            Cache cache = manager.getCache(cacheName);
            cache.removeAll();
        } catch (Exception e) {

            log.error("删除全部失败：{}", e.getMessage());
        }
    }

    public void put(String cacheName, String key, Object value) {
        try {
            Cache cache = manager.getCache(cacheName);
            Element element = new Element(key, value);
            cache.put(element);
        } catch (Exception e) {

            log.error("添加缓存失败：{}", e.getMessage());
        }
    }


    public void putUser(String key, Object value) {
        Cache cache = manager.getCache("users");
        Element element = new Element(key, value);
        cache.put(element);
    }

    public Object get(String cacheName, String key) {
        try {
            Cache cache = manager.getCache(cacheName);
            Element element = cache.get(key);
            return element == null ? null : element.getObjectValue();
        } catch (Exception e) {

            log.error("获取缓存数据失败：{}", e.getMessage());
            return null;
        }
    }

    public UserInfo getUser(String key) {
        Cache cache = manager.getCache("users");
        Element element = cache.get(key);
        return element == null ? null : (UserInfo) element.getObjectValue();
    }


    public void delete(String cacheName, String key) {
        try {
            Cache cache = manager.getCache(cacheName);
            cache.remove(key);
        } catch (Exception e) {

            log.error("删除缓存数据失败：{}", e.getMessage());
        }
    }


}
